// ========== 启动界面逻辑 ======
document.addEventListener('DOMContentLoaded', function() {
    // 获取启动界面相关元素
    var startScreen = document.getElementById('startScreen');
    var mainGame = document.getElementById('mainGame');
    var startBtn = document.getElementById('startBtn');
    var startNameInput = document.getElementById('startNameInput');
    var startLevelSelect = document.getElementById('startLevelSelect');

    // 进入游戏函数
    function enterGame() {
        // 获取玩家输入的名字，若为空则默认为'游客'
        var name = startNameInput.value.trim() || '游客';
        // 获取关卡选择，若无效则默认为1
        var level = parseInt(startLevelSelect.value) || 1;
        
        // 设置游戏内的玩家名字和关卡
        document.getElementById('playerNameInput').value = name;
        document.getElementById('levelSelect').value = level;
        
        // 触发游戏内的关卡选择事件
        document.getElementById('playerNameBtn').click();
        document.getElementById('levelSelect').dispatchEvent(new Event('change'));
        
        // 启动界面淡出效果
        startScreen.style.animation = 'fadeOut 0.7s forwards';
        setTimeout(function() {
            startScreen.style.display = 'none';
            mainGame.style.display = '';
        }, 700);
    }

    // 设置按钮点击和键盘回车事件
    startBtn.onclick = enterGame;
    startNameInput.onkeydown = function(e) {
        if (e.key === 'Enter') enterGame();
    };
    startLevelSelect.onkeydown = function(e) {
        if (e.key === 'Enter') enterGame();
    };
    startBtn.onkeydown = function(e) {
        if (e.key === 'Enter') enterGame();
    };
});

// 创建淡出动画样式
var style = document.createElement('style');
style.innerHTML = '@keyframes fadeOut { from { opacity: 1; } to { opacity: 0; }}';
document.head.appendChild(style);

// ========== 游戏常量 ==========
// 定义游戏基本常量
var CELL_SIZE = 20;
var ROWS = 21;
var COLS = 28;
var PACMAN_SIZE = 14;
var MAX_LEVEL = 3;
var DOT_TYPE = { NORMAL: 0, SUPER: 1 }; // 定义豆子类型

// ========== 关卡配置 ==========
// 定义三个关卡的配置信息
var levels = [
    { // 初级关卡
        name: "初级迷宫",
        template: [ // 迷宫模板
            "############################",
            "#..........................#",
            "#.########################.#",
            "#.#......................#.#",
            "#.#.####################.#.#",
            "#.#.#..................#.#.#",
            "#.#.#.############.#.#.#.#.#",
            "#.#.#..............#.#.#.#.#",
            "#.#.#.#.######.#.#.#.#.#.#.#",
            "#.#.#.#....P...#.#.#.#.#.#.#",
            "#.#.#.##########.#.#.#.#.#.#",
            "#.#.#..............#.#.#.#.#",
            "#.#.#.############.#.#.#.#.#",
            "#.#................#.#.#.#.#",
            "#.#.##############.#.#.#.#.#",
            "#.#........................#",
            "#.#.######################.#",
            "#.#........................#",
            "#.#.######################.#",
            "#..........................#",
            "############################"
        ],
        speed: 70, // 幽灵速度
        ghostType: ['classic'], // 幽灵类型
        superDots: [{x:2,y:1},{x:25,y:1},{x:2,y:19},{x:25,y:19}] // 超级豆位置
    },
    { // 中级关卡
        name: "进阶迷宫",
        template: [ // 迷宫模板
            "############################",
            "#..........................#",
            "#.##########..##########...#",
            "#.#......##....##......#.#.#",
            "#.#.##..####..####..##.#.#.#",
            "#.#....................#.#.#",
            "#.#####..######..#####.#.#.#",
            "#......#...P...........#.#.#",
            "#############.##########.#.#",
            "#......#........#......#.#.#",
            "#.#####..######..#####.#.#.#",
            "#.#....................#.#.#",
            "#.#.##..####..####..##.#.#.#",
            "#.#......##....##......#.#.#",
            "#.##########..##########.#.#",
            "#.......##.......##........#",
            "#..........................#",
            "#...#####........###.#####.#",
            "#...........#####..........#",
            "#.....#####................#",
            "############################"
        ],
        speed: 50,
        ghostType: ['classic','spike'],
        superDots: [{x:3,y:2},{x:24,y:2},{x:3,y:18},{x:24,y:18}]
    },
    { // 高级关卡
        name: "终极迷宫",
        template: [ // 迷宫模板
            "############################",
            "#............##............#",
            "#.######..######..######...#",
            "#.#....#......#....#.......#",
            "#.#.##.######.##.##.##.#...#",
            "#.#.......###.......##.....#",
            "#.######..###.###..######..#",
            "#......#....P....#.........#",
            "#.#####..###################",
            "#......#........#......##..#",
            "#.######..#######..#######.#",
            "#.#.....................#..#",
            "#.#..######.##.##.##.#..#..#",
            "#.#....#......#....#......##",
            "#.######..######..######.#.#",
            "#...##.....##.....####...#.#",
            "#..##........##...####.....#",
            "#....#...#..##......####...#",
            "#.#..####....##...##.....###",
            "#.#..####.#..##...##..#..###",
            "############################"
        ],
        speed: 40,
        ghostType: ['classic','spike','boss'],
        superDots: [{x:3,y:1},{x:24,y:1},{x:3,y:19},{x:24,y:19}]
    }
];

// ========== 游戏状态 ==========
var gameState = {
    active: true,
    pacman: {},
    ghosts: [],
    dots: [],
    score: 0,
    level: 1,
    map: [],
    ghostMoveCounter: 0,
    scores: [],
    player: { name: '游客', isInvincible: false, invincibleTimer: 0 },
    leaderboard: []
};

// ========== 工具函数 ==========
// 检查位置是否有效
function isValidPosition(x, y) {
    return y >= 0 && y < ROWS && x >= 0 && x < COLS && gameState.map[y][x] !== '#';
}

// 显示提示信息
function showTip(msg) {
    var tip = document.getElementById('tipMsg');
    tip.textContent = msg;
    tip.style.opacity = 1;
    setTimeout(function() {
        tip.style.opacity = 0;
    }, 2000);
}

// 字符串填充函数
function padEnd(str, length, char) {
    while (str.length < length) {
        str += char;
    }
    return str;
}

// ========== 初始化 ==========
// 初始化游戏
function initGame(selectedLevel) {
    // 设置游戏为活跃状态
    gameState.active = true;
    
    // 获取当前关卡配置
    var levelConfig = levels[selectedLevel !== undefined ? selectedLevel : (gameState.level-1)];
    
    // 初始化地图
    gameState.map = [];
    for (var i = 0; i < ROWS; i++) {
        gameState.map[i] = [];
        for (var j = 0; j < COLS; j++) {
            gameState.map[i][j] = '#';
        }
    }
    
    // 重置豆子和幽灵数组
    gameState.dots = [];
    gameState.ghosts = [];
    
    // 根据关卡模板设置地图
    for (var y = 0; y < levelConfig.template.length; y++) {
        var row = levelConfig.template[y];
        var paddedRow = padEnd(row, COLS, '#').slice(0, COLS);
        for (var x = 0; x < COLS; x++) {
            if (y < ROWS) {
                gameState.map[y][x] = paddedRow[x];
                
                // 收集普通豆子位置
                if (paddedRow[x] === '.') {
                    gameState.dots.push({x: x, y: y, type: DOT_TYPE.NORMAL});
                }
                
                // 设置Pac-Man初始位置
                if (paddedRow[x] === 'P') {
                    gameState.pacman.x = x;
                    gameState.pacman.y = y;
                    gameState.pacman.dir = 0;
                }
            }
        }
    }
    
    // 设置超级豆子
    for (var i = 0; i < levelConfig.superDots.length; i++) {
        var dot = levelConfig.superDots[i];
        if (gameState.map[dot.y] && gameState.map[dot.y][dot.x] === '.') {
            gameState.dots.push({
                x: dot.x,
                y: dot.y,
                type: DOT_TYPE.SUPER
            });
        } else {
            console.warn('Invalid super dot position:', dot);
        }
    }
    
    // 创建幽灵
    for (var i = 0; i < levelConfig.ghostType.length; i++) {
        var type = levelConfig.ghostType[i];
        var ghostPos;
        do {
            // 随机位置生成幽灵
            ghostPos = {
                x: Math.floor(Math.random() * (COLS-4)) + 2,
                y: Math.floor(Math.random() * (ROWS-4)) + 2
            };
        } while (gameState.map[ghostPos.y][ghostPos.x] !== '.');
        
        gameState.ghosts.push({
            x: ghostPos.x,
            y: ghostPos.y,
            type: type,
            color: ['#FF5555','#55FF55','#5555FF','#FFAA00'][i%4],
            speed: levelConfig.speed + i*10,
            direction: 0,
            moveCounter: 0
        });
    }
    
    // 绘制游戏
    draw();
}

// ========== 绘制逻辑 ==========
// 绘制游戏画面
function draw() {
    var ctx = canvas.getContext('2d');
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制背景
    ctx.fillStyle = '#23243a';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制迷宫墙壁
    for (var y = 0; y < gameState.map.length; y++) {
        for (var x = 0; x < gameState.map[y].length; x++) {
            if (gameState.map[y][x] === '#') {
                var grad = ctx.createLinearGradient(x*CELL_SIZE, y*CELL_SIZE, (x+1)*CELL_SIZE, (y+1)*CELL_SIZE);
                grad.addColorStop(0, "#00f0ff");
                grad.addColorStop(1, "#a020f0");
                ctx.fillStyle = grad;
                ctx.shadowColor = "#00f0ff";
                ctx.shadowBlur = 10;
                ctx.fillRect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE);
                ctx.shadowBlur = 0;
            }
        }
    }
    
    // 绘制豆子
    for (var i = 0; i < gameState.dots.length; i++) {
        var dot = gameState.dots[i];
        if (dot.type === DOT_TYPE.NORMAL) {
            ctx.fillStyle = '#f1c40f';
            ctx.beginPath();
            ctx.arc(dot.x*CELL_SIZE+CELL_SIZE/2, dot.y*CELL_SIZE+CELL_SIZE/2, 3, 0, Math.PI*2);
            ctx.fill();
        } else if (dot.type === DOT_TYPE.SUPER) {
            ctx.save();
            ctx.shadowColor = '#ffe066';
            ctx.shadowBlur = 12;
            ctx.fillStyle = '#ffe066';
            ctx.beginPath();
            ctx.arc(dot.x*CELL_SIZE+CELL_SIZE/2, dot.y*CELL_SIZE+CELL_SIZE/2, 6, 0, Math.PI*2);
            ctx.fill();
            ctx.restore();
        }
    }
    
    // 绘制Pac-Man
    ctx.save();
    ctx.shadowColor = gameState.player.isInvincible ? '#00f0ff' : '#f1c40f';
    ctx.shadowBlur = gameState.player.isInvincible ? 16 : 8;
    ctx.fillStyle = gameState.player.isInvincible ? '#00f0ff' : '#f1c40f';
    ctx.beginPath();
    ctx.arc(
        gameState.pacman.x*CELL_SIZE+CELL_SIZE/2,
        gameState.pacman.y*CELL_SIZE+CELL_SIZE/2,
        PACMAN_SIZE,
        0.2*Math.PI + gameState.pacman.dir*0.5,
        1.8*Math.PI + gameState.pacman.dir*0.5
    );
    ctx.lineTo(gameState.pacman.x*CELL_SIZE+CELL_SIZE/2, gameState.pacman.y*CELL_SIZE+CELL_SIZE/2);
    ctx.fill();
    ctx.restore();
    
    // 绘制幽灵
    for (var i = 0; i < gameState.ghosts.length; i++) {
        var ghost = gameState.ghosts[i];
        var dx = gameState.pacman.x - ghost.x;
        var dy = gameState.pacman.y - ghost.y;
        var len = Math.sqrt(dx*dx + dy*dy) || 1;
        var ex = (dx/len) * 2;
        var ey = (dy/len) * 2;
        drawGhost(ctx, ghost.x, ghost.y, ghost.color, ex, ey, gameState.player.isInvincible);
    }
}

// 绘制幽灵的辅助函数
function drawGhost(ctx, x, y, color, eyeDx, eyeDy, scared) {
    var cx = x * CELL_SIZE + CELL_SIZE / 2;
    var cy = y * CELL_SIZE + CELL_SIZE / 2;
    var r = PACMAN_SIZE * 0.9;
    var footCount = 4;
    var footWidth = r * 2 / footCount;
    var baseY = cy + r;

    ctx.save();
    ctx.beginPath();
    ctx.arc(cx, cy, r, Math.PI, 0, false);
    ctx.lineTo(cx + r, baseY);
    for (var i = footCount; i > 0; i--) {
        var fx = cx - r + footWidth * i;
        var fy = baseY + (i % 2 === 0 ? 0 : 4);
        ctx.lineTo(fx, fy);
    }
    ctx.lineTo(cx - r, baseY);
    ctx.closePath();
    ctx.fillStyle = scared ? '#00f0ff' : color;
    ctx.shadowColor = scared ? '#00f0ff' : color;
    ctx.shadowBlur = 8;
    ctx.fill();
    ctx.shadowBlur = 0;

    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(cx - 5, cy - 2, 3, 0, Math.PI * 2);
    ctx.arc(cx + 5, cy - 2, 3, 0, Math.PI * 2);
    ctx.fill();

    ctx.fillStyle = "#222";
    ctx.beginPath();
    ctx.arc(cx - 5 + eyeDx, cy - 2 + eyeDy, 1.2, 0, Math.PI * 2);
    ctx.arc(cx + 5 + eyeDx, cy - 2 + eyeDy, 1.2, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
}

// ========== 游戏逻辑 ==========
// 移动幽灵
function moveGhosts() {
    for (var i = 0; i < gameState.ghosts.length; i++) {
        var ghost = gameState.ghosts[i];
        ghost.moveCounter++;
        if (ghost.moveCounter < ghost.speed) continue;
        ghost.moveCounter = 0;
        
        // 定义四个方向
        var directions = [
            {dx:0, dy:-1}, {dx:0, dy:1}, {dx:-1, dy:0}, {dx:1, dy:0}
        ];
        
        var bestDir = null, bestScore = gameState.player.isInvincible ? -Infinity : Infinity;
        
        // 计算最佳移动方向
        for (var j = 0; j < directions.length; j++) {
            var dir = directions[j];
            var nx = ghost.x + dir.dx, ny = ghost.y + dir.dy;
            if (isValidPosition(nx, ny)) {
                var dist = Math.abs(nx - gameState.pacman.x) + Math.abs(ny - gameState.pacman.y);
                if (gameState.player.isInvincible) {
                    if (dist > bestScore) { bestScore = dist; bestDir = dir; }
                } else {
                    if (dist < bestScore) { bestScore = dist; bestDir = dir; }
                }
            }
        }
        
        // 移动幽灵
        if (bestDir && Math.random() < 0.8) {
            ghost.x += bestDir.dx;
            ghost.y += bestDir.dy;
        } else {
            var availableDirs = [];
            for (var j = 0; j < directions.length; j++) {
                var dir = directions[j];
                if (isValidPosition(ghost.x+dir.dx, ghost.y+dir.dy)) {
                    availableDirs.push(dir);
                }
            }
            if (availableDirs.length > 0) {
                var dir = availableDirs[Math.floor(Math.random()*availableDirs.length)];
                ghost.x += dir.dx;
                ghost.y += dir.dy;
            }
        }
    }
}

// 吃豆子
function eatDot() {
    var dotIndex = -1;
    for (var i = 0; i < gameState.dots.length; i++) {
        if (gameState.dots[i].x === gameState.pacman.x && gameState.dots[i].y === gameState.pacman.y) {
            dotIndex = i;
            break;
        }
    }
    
    if (dotIndex > -1) {
        var dot = gameState.dots[dotIndex];
        gameState.dots.splice(dotIndex, 1);
        
        // 增加分数
        if (dot.type === DOT_TYPE.NORMAL) {
            gameState.score += 10;
        } else if (dot.type === DOT_TYPE.SUPER) {
            gameState.score += 50;
            // 激活无敌模式
            gameState.player.isInvincible = true;
            gameState.player.invincibleTimer = 200;
            showTip('超级豆！短暂无敌！');
        }
        document.getElementById('score').textContent = gameState.score;
    }
}

// 检查幽灵碰撞
function checkGhostCollision() {
    if (gameState.player.isInvincible) return;
    for (var i = 0; i < gameState.ghosts.length; i++) {
        var ghost = gameState.ghosts[i];
        if (Math.abs(ghost.x - gameState.pacman.x) < 1 && Math.abs(ghost.y - gameState.pacman.y) < 1) {
            showGameOver();
        }
    }
}

// 显示关卡完成
function showLevelComplete() {
    gameState.active = false;
    // 保存分数
    gameState.scores.push(gameState.score);
    saveScores(gameState.scores);
    updateLeaderboard();
    showScoreChart(gameState.scores, document.getElementById('chartTypeBtn').dataset.type || 'bar');
    
    // 显示自定义弹窗
    var popup = document.getElementById('levelCompletePopup');
    document.getElementById('currentLevelName').textContent = '关卡 ' + gameState.level;
    document.getElementById('levelScore').textContent = gameState.score;
    
    popup.classList.remove('hidden');
    
    // 设置弹窗按钮事件
    document.getElementById('nextLevelBtn').onclick = function() {
        if (gameState.level < MAX_LEVEL) {
            // 进入下一关
            gameState.level++;
            document.getElementById('level').textContent = gameState.level;
            document.getElementById('levelSelect').value = gameState.level;
            initGame();
            gameLoop();
        } else {
            // 游戏胜利
            alert('最终胜利！总得分：' + gameState.score);
            gameState.level = 1;
            document.getElementById('level').textContent = 1;
            document.getElementById('levelSelect').value = 1;
            gameState.score = 0;
            document.getElementById('score').textContent = 0;
            initGame();
            gameLoop();
        }
        popup.classList.add('hidden');
    };
    
    document.getElementById('stayLevelBtn').onclick = function() {
        // 重新开始当前关
        gameState.score = 0;
        document.getElementById('score').textContent = 0;
        document.getElementById('levelSelect').value = gameState.level;
        initGame(gameState.level - 1);
        gameLoop();
        popup.classList.add('hidden');
    };
}

// 显示游戏结束
function showGameOver() {
    gameState.active = false;
    // 保存分数
    gameState.scores.push(gameState.score);
    saveScores(gameState.scores);
    updateLeaderboard();
    showScoreChart(gameState.scores, document.getElementById('chartTypeBtn').dataset.type || 'bar');
    
    // 询问是否重新开始
    var currentLevel = gameState.level;
    var restart = confirm('游戏结束！得分：' + gameState.score + '\n是否重新开始当前关卡？');
    
    if (restart) {
        gameState.score = 0;
        document.getElementById('score').textContent = 0;
        document.getElementById('levelSelect').value = currentLevel;
        initGame(currentLevel - 1);
        gameLoop();
    } else {
        gameState.level = 1;
        document.getElementById('level').textContent = 1;
        document.getElementById('levelSelect').value = 1;
        gameState.score = 0;
        document.getElementById('score').textContent = 0;
        initGame();
        gameLoop();
    }
}

// ========== 主循环 ==========
// 游戏主循环
function gameLoop() {
    if (!gameState.active) return;
    
    try {
        // 移动幽灵
        moveGhosts();
        
        // 吃豆子
        eatDot();
        
        // 检查是否吃完所有豆子
        if (gameState.dots.length === 0) { 
            showLevelComplete(); 
            return; 
        }
        
        // 检查幽灵碰撞
        checkGhostCollision();
        
        // 处理无敌时间
        if (gameState.player.isInvincible) {
            gameState.player.invincibleTimer--;
            if (gameState.player.invincibleTimer <= 0) {
                gameState.player.isInvincible = false;
                showTip('无敌结束！小心幽灵！');
            }
        }
        
        // 绘制游戏
        draw();
        requestAnimationFrame(gameLoop);
    } catch (e) {
        showTip('发生错误：' + e.message);
    }
}

// ========== 事件监听 ==========
// 键盘控制
document.addEventListener('keydown', function(e) {
    if (["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.key) > -1) e.preventDefault();
    if (!gameState.active) return;
    
    var directions = {
        ArrowUp: {dx:0, dy:-1, dir:0},
        ArrowDown: {dx:0, dy:1, dir:1},
        ArrowLeft: {dx:-1, dy:0, dir:2},
        ArrowRight: {dx:1, dy:0, dir:3}
    };
    
    if (directions[e.key]) {
        var dir = directions[e.key];
        var nextX = gameState.pacman.x + dir.dx, nextY = gameState.pacman.y + dir.dy;
        if (isValidPosition(nextX, nextY)) {
            gameState.pacman.x = nextX; 
            gameState.pacman.y = nextY; 
            gameState.pacman.dir = dir.dir;
        }
    }
});

// 重新开始按钮
document.getElementById('restartBtn').onclick = function() {
    var currentLevel = gameState.level;
    gameState.score = 0;
    document.getElementById('score').textContent = 0;
    document.getElementById('levelSelect').value = currentLevel;
    initGame(currentLevel - 1);
    gameLoop();
};

// 玩家名字按钮
document.getElementById('playerNameBtn').onclick = function() {
    var name = document.getElementById('playerNameInput').value.trim();
    if (name) gameState.player.name = name;
    showTip('欢迎，' + gameState.player.name + '！');
};

// 关卡选择
document.getElementById('levelSelect').onchange = function(e) {
    gameState.level = parseInt(e.target.value);
    document.getElementById('level').textContent = gameState.level;
    gameState.score = 0;
    document.getElementById('score').textContent = 0;
    initGame(gameState.level-1);
    gameLoop();
};

// ========== 数据存储 ==========
// 保存分数
function saveScores(arr) {
    localStorage.setItem('pacman_scores', JSON.stringify(arr));
}

// 加载分数
function loadScores() {
    var s = localStorage.getItem('pacman_scores');
    return s ? JSON.parse(s) : [];
}

// 保存排行榜
function saveLeaderboard(arr) {
    localStorage.setItem('pacman_leaderboard', JSON.stringify(arr));
}

// 加载排行榜
function loadLeaderboard() {
    var s = localStorage.getItem('pacman_leaderboard');
    return s ? JSON.parse(s) : [];
}

// 更新排行榜
function updateLeaderboard() {
    gameState.leaderboard = loadLeaderboard();
    gameState.leaderboard.push({
        name: gameState.player.name,
        score: gameState.score,
        date: new Date().toLocaleString()
    });
    gameState.leaderboard.sort(function(a, b) {
        return b.score - a.score;
    });
    gameState.leaderboard = gameState.leaderboard.slice(0, 10);
    saveLeaderboard(gameState.leaderboard);
    renderLeaderboard();
}

// 渲染排行榜
function renderLeaderboard() {
    var html = '';
    for (var i = 0; i < gameState.leaderboard.length; i++) {
        var item = gameState.leaderboard[i];
        html += '<li data-rank="' + (i+1) + '">' + item.name + '：' + item.score + '分 (' + item.date + ')</li>';
    }
    document.getElementById('leaderboard').innerHTML = html;
}

// 排行榜首击事件
document.getElementById('leaderboard').onclick = function(e) {
    if (e.target.dataset.rank) {
        showTip('第' + e.target.dataset.rank + '名：' + e.target.textContent);
    }
};

// ========== 图表功能 ==========
// 显示分数图表
function showScoreChart(scores, type) {
    type = type || 'bar';
    var chartDom = document.getElementById('scoreChart');
    var myChart = echarts.init(chartDom);
    var option = {
        title: { 
            text: '历史得分',
            left: 'center',
            textStyle: {
                color: '#ffe066',
                fontSize: 22,
                fontWeight: 'bold',
                textShadowColor: '#ffe066',
                textShadowBlur: 8
            }
        },
        xAxis: { 
            type: 'category',
            data: (function() {
                var arr = [];
                for (var i = 0; i < scores.length; i++) {
                    arr.push('第' + (i+1) + '局');
                }
                return arr;
            })(),
            axisLabel: {color:'#fff'}
        },
        yAxis: { type: 'value', axisLabel: {color:'#fff'} },
        series: [{ 
            data: scores,
            type: type === 'pie' ? 'pie' : type,
            itemStyle: { color: '#ffe066' },
            label: { show: true, position: 'top', color:'#ffe066', fontWeight:'bold' },
            radius: type === 'pie' ? '60%' : undefined,
            center: type === 'pie' ? ['50%', '60%'] : undefined,
            label: type === 'pie' ? {formatter: '{b}: {c}'} : { show: true, position: 'top', color:'#ffe066', fontWeight:'bold' },
            data: type === 'pie' ? (function() {
                var arr = [];
                for (var i = 0; i < scores.length; i++) {
                    arr.push({value: scores[i], name: '第' + (i+1) + '局'});
                }
                return arr;
            })() : scores
        }],
        grid: { left: 40, right: 20, bottom: 40, top: 60 }
    };
    myChart.setOption(option);
}

// 图表类型切换
document.getElementById('chartTypeBtn').onclick = function() {
    var type = this.dataset.type === 'bar' ? 'line' : (this.dataset.type === 'line' ? 'pie' : 'bar');
    this.dataset.type = type;
    showScoreChart(gameState.scores, type);
};

// ========== 初始化游戏 ==========
// 获取游戏画布
var canvas = document.getElementById('gameCanvas');
window.onload = function() {
    // 加载历史分数和排行榜
    gameState.scores = loadScores();
    gameState.leaderboard = loadLeaderboard();
    // 显示分数图表和排行榜
    showScoreChart(gameState.scores);
    renderLeaderboard();
    // 初始化第一关
    initGame();
    // 启动游戏循环
    gameLoop();
};

// ========== 错误处理 ==========
// 错误处理
window.onerror = function(msg, url, line, col, error) {
    showTip('发生错误：' + msg);
    return true;
};